<template>
  <div class="chat-system">
    <!-- 顶部导航 -->
    <header class="chat-header">
      <h1>实时聊天系统</h1>
      <div class="user-info">
        <span>当前用户: {{ currentUser.username }}</span>
        <button @click="logout" class="logout-btn">退出</button>
      </div>
    </header>
    
    <div class="chat-container">
      <!-- 侧边栏 - 在线用户列表 -->
      <aside class="sidebar">
        <!-- 侧边栏内容保持不变 -->
        <div class="sidebar-header">
          <h2>在线用户 ({{ onlineUsers.length }})</h2>
          <button @click="refreshUserList" class="refresh-btn">
            <i class="fas fa-sync"></i>
          </button>
        </div>
        
        <div class="user-list">
          <div 
            class="user-item"
            :class="{ active: currentChatTarget.id === 'all' }"
            @click="setChatTarget('all', '全体成员')"
          >
            <div class="user-avatar">
              <i class="fas fa-users"></i>
            </div>
            <div class="user-details">
              <div class="user-name">全体成员</div>
              <div class="user-status">群聊</div>
            </div>
          </div>
          
          <div 
            v-for="user in onlineUsers" 
            :key="user.id"
            class="user-item"
            :class="{ 
              active: currentChatTarget.id === user.id,
              self: user.id === currentUser.id
            }"
            @click="setChatTarget(user.id, user.username)"
          >
            <div class="user-avatar">
              <span>{{ user.username.charAt(0) }}</span>
            </div>
            <div class="user-details">
              <div class="user-name">
                {{ user.username }}
                <span v-if="user.id === currentUser.id">(我)</span>
              </div>
              <div class="user-status" :class="user.status">
                {{ formatStatus(user.status) }}
              </div>
            </div>
          </div>
        </div>
      </aside>
      
      <!-- 主聊天区域 -->
      <main class="chat-area">
        <div class="chat-header">
          <h2>
            {{ currentChatTarget.name }}
            <span v-if="currentChatTarget.id !== 'all'" class="private-tag">私聊</span>
          </h2>
          <div class="connection-status" :class="connectionStatus">
            <span class="status-indicator"></span>
            {{ connectionStatusText }}
          </div>
        </div>
        
        <!-- 聊天消息区域 -->
        <div class="messages" ref="messagesContainer">
          <div 
            v-for="(msg, index) in filteredMessages" 
            :key="msg.id || index"
            class="message"
            :class="{ sent: msg.senderId === currentUser.id }"
          >
            <div v-if="msg.type === 'system'" class="system-message">
              {{ msg.data.message }}
              <div class="message-time">{{ formatTime(msg.data.timestamp) }}</div>
            </div>
            
            <div v-else>
              <div v-if="!msg.sent" class="message-sender">{{ msg.username }}</div>
              <div class="message-content" v-html="formatMessageWithEmojis(msg.content)"></div>
              <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
              <div v-if="msg.sent" class="message-self">我</div>
            </div>
          </div>
        </div>
        
        <!-- 消息输入区域 - 添加表情功能 -->
        <div class="message-input-area">
          <div class="emoji-container">
            <!-- 表情按钮 -->
            <button 
              class="emoji-btn" 
              @click="showEmojiPanel = !showEmojiPanel"
            >
            <el-icon  class="far fa-smile"><ElemeFilled /></el-icon>
            </button>
            
            <!-- 表情面板 -->
            <div 
              class="emoji-panel" 
              v-if="showEmojiPanel"
              @click.stop
            >
              <div class="emoji-category">
                <h4>常用表情</h4>
                <div class="emoji-grid">
                  <span 
                    v-for="(emoji, key) in emojis" 
                    :key="key"
                    class="emoji-item"
                    @click="insertEmoji(emoji)"
                  >
                    {{ emoji }}
                  </span>
                </div>
              </div>
            </div>
          </div>
          
          <textarea
            v-model="messageContent"
            @keyup.enter="sendMessage"
            placeholder="输入消息，按Enter发送..."
            :disabled="!isConnected"
            ref="messageInput"
          ></textarea>
          <button 
            @click="sendMessage" 
            class="send-btn"
            :disabled="!messageContent.trim() || !isConnected"
          > 发送
            <i class="fas fa-paper-plane"></i>
          </button>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, nextTick } from 'vue';

// API基础URL
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001';
const WS_BASE_URL = import.meta.env.VITE_WS_URL || 'ws://localhost:3001';

// 状态管理
const currentUser = ref({ id: null, username: '' });
const onlineUsers = ref([]);
const messages = ref([]);
const messageContent = ref('');
const currentChatTarget = ref({ id: 'all', name: '全体成员' });
const connectionStatus = ref('disconnected'); // connected, connecting, disconnected
const ws = ref(null);
const messagesContainer = ref(null);
const messageInput = ref(null);

// 表情相关状态
const showEmojiPanel = ref(false);
const emojis = ref([
  '😀', '😁', '😂', '🤣', '😃', '😄', '😅', '😆', '😉', '😊',
  '🙂', '🙃', '😋', '😎', '😍', '😘', '🥰', '😗', '😙', '👍',
  '👎', '👊', '✊', '🤝', '🙌', '👏', '🎉', '🎊', '🔥', '❤️',
  '💔', '👍', '👎', '❤️', '💯', '✨', '🌟', '🎁', '🎈', '🎂'
]);

// 计算属性
const isConnected = computed(() => connectionStatus.value === 'connected');
const connectionStatusText = computed(() => {
  const statusMap = {
    connected: '已连接',
    connecting: '连接中...',
    disconnected: '未连接'
  };
  return statusMap[connectionStatus.value] || '未知状态';
});

// 过滤当前聊天目标的消息
const filteredMessages = computed(() => {
  if (currentChatTarget.value.id === 'all') {
    return messages.value.filter(msg => 
      msg.target === 'all' || msg.type === 'system'
    );
  }
  
  return messages.value.filter(msg => 
    msg.type === 'system' ||
    msg.target === currentChatTarget.value.id ||
    (msg.senderId === currentChatTarget.value.id && msg.target === currentUser.value.id)
  );
});

// 格式化状态显示
const formatStatus = (status) => {
  const statusMap = {
    online: '在线',
    away: '离开',
    busy: '忙碌'
  };
  return statusMap[status] || status;
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

// 格式化消息内容，处理表情显示
const formatMessageWithEmojis = (content) => {
  // 这里直接返回内容，因为我们使用原生emoji字符
  // 如果使用图片表情，这里需要替换为img标签
  return content;
};

// 插入表情到输入框
const insertEmoji = (emoji) => {
  // 在光标位置插入表情
  const textarea = messageInput.value;
  if (!textarea) return;
  
  const start = textarea.selectionStart;
  const end = textarea.selectionEnd;
  const currentValue = messageContent.value;
  
  // 插入表情
  messageContent.value = 
    currentValue.substring(0, start) + 
    emoji + 
    currentValue.substring(end);
  
  // 移动光标到表情后面
  nextTick(() => {
    const newPosition = start + emoji.length;
    textarea.focus();
    textarea.setSelectionRange(newPosition, newPosition);
  });
};

// API调用：获取在线用户列表
const fetchOnlineUsers = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/online-users`);
    const data = await response.json();
    if (data.success) {
      onlineUsers.value = data.data;
    }
  } catch (error) {
    console.error('获取在线用户失败:', error);
  }
};

// API调用：获取聊天记录
const fetchChatHistory = async (target = 'all') => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/chat-history?target=${target}`);
    const data = await response.json();
    if (data.success) {
      messages.value = data.data;
      scrollToBottom();
    }
  } catch (error) {
    console.error('获取聊天记录失败:', error);
  }
};

// API调用：发送消息（HTTP备用方法）
const sendMessageViaHttp = async (content, target) => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/send-message`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        clientId: currentUser.value.id,
        content,
        target
      })
    });
    
    const data = await response.json();
    if (data.success) {
      messages.value.push(data.data);
      messageContent.value = '';
      scrollToBottom();
    }
  } catch (error) {
    console.error('发送消息失败:', error);
  }
};

// 发送消息（优先使用WebSocket）
const sendMessage = () => {
  const content = messageContent.value.trim();
  if (!content || !isConnected.value) return;
  
  // 隐藏表情面板
  showEmojiPanel.value = false;
  
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    // 使用WebSocket发送
    ws.value.send(JSON.stringify({
      type: 'message',
      content
    }));
    messageContent.value = '';
  } else {
    // 备用：使用HTTP发送
    sendMessageViaHttp(content, currentChatTarget.value.id);
  }
};

// 滚动到最新消息
const scrollToBottom = async () => {
  await nextTick();
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 其他方法保持不变...
const setChatTarget = (targetId, targetName) => {
  currentChatTarget.value = { id: targetId, name: targetName };
  fetchChatHistory(targetId).then(() => {
    scrollToBottom();
  });
  
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.send(JSON.stringify({
      type: 'changeChatTarget',
      targetId
    }));
  }
};

const refreshUserList = () => {
  fetchOnlineUsers();
};

const logout = () => {
  if (ws.value) {
    ws.value.close();
  }
  currentUser.value = { id: null, username: '' };
  messages.value = [];
  onlineUsers.value = [];
};

// WebSocket连接
const connectWebSocket = () => {
  if (ws.value) {
    ws.value.close();
  }
  
  connectionStatus.value = 'connecting';
  
  try {
    ws.value = new WebSocket(WS_BASE_URL);
    
    ws.value.onopen = () => {
      console.log('WebSocket连接成功');
      connectionStatus.value = 'connected';
      
      ws.value.send(JSON.stringify({
        type: 'join',
        username: currentUser.value.username || `用户${Math.floor(Math.random() * 1000)}`
      }));
    };
    
    ws.value.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        handleWebSocketMessage(data);
      } catch (error) {
        console.error('解析WebSocket消息失败:', error);
      }
    };
    
    ws.value.onclose = () => {
      console.log('WebSocket连接关闭');
      connectionStatus.value = 'disconnected';
      setTimeout(connectWebSocket, 3000);
    };
    
    ws.value.onerror = (error) => {
      console.error('WebSocket错误:', error);
      connectionStatus.value = 'disconnected';
    };
  } catch (error) {
    console.error('建立WebSocket连接失败:', error);
    connectionStatus.value = 'disconnected';
  }
};

const handleWebSocketMessage = (data) => {
  switch (data.type) {
    case 'init':
      currentUser.value = {
        id: data.data.clientId,
        username: data.data.username
      };
      onlineUsers.value = data.data.onlineUsers;
      break;
      
    case 'message':
      messages.value.push(data.data);
      scrollToBottom();
      break;
      
    case 'system':
      messages.value.push(data);
      scrollToBottom();
      break;
      
    case 'userList':
      onlineUsers.value = data.data;
      break;
      
    case 'chatTargetChanged':
      currentChatTarget.value = {
        id: data.data.targetId,
        name: data.data.targetName
      };
      break;
  }
};

// 监听消息变化
watch(
  () => filteredMessages.value,
  () => {
    scrollToBottom();
  },
  { deep: true }
);

// 点击页面其他区域关闭表情面板
document.addEventListener('click', (e) => {
  const emojiContainer = document.querySelector('.emoji-container');
  if (emojiContainer && !emojiContainer.contains(e.target)) {
    showEmojiPanel.value = false;
  }
});

// 组件挂载时初始化
onMounted(() => {
  connectWebSocket();
  fetchOnlineUsers();
  fetchChatHistory();
});
</script>

<style scoped>
.chat-system {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  color: #333;
  overflow: hidden;
}

.chat-header {
  background-color: #2c3e50;
  color: white;
  padding: 1rem 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.logout-btn {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.logout-btn:hover {
  background-color: #c0392b;
}

.chat-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 280px;
  background-color: white;
  border-right: 1px solid #ddd;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 1rem;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.refresh-btn {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.refresh-btn:hover {
  background-color: #f5f5f5;
}

.user-list {
  flex: 1;
  overflow-y: auto;
  padding: 0.5rem;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 0.75rem;
  border-radius: 8px;
  margin-bottom: 0.5rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-item:hover {
  background-color: #f5f5f5;
}

.user-item.active {
  background-color: #e3f2fd;
  border-left: 3px solid #3498db;
}

.user-item.self .user-avatar {
  background-color: #2ecc71;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #3498db;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 1rem;
}

.user-details {
  flex: 1;
}

.user-name {
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.user-status {
  font-size: 0.8rem;
  padding: 2px 6px;
  border-radius: 4px;
}

.user-status.online {
  background-color: rgba(46, 204, 113, 0.1);
  color: #27ae60;
}

.user-status.away {
  background-color: rgba(243, 156, 18, 0.1);
  color: #d35400;
}

.user-status.busy {
  background-color: rgba(231, 76, 60, 0.1);
  color: #c0392b;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-area .chat-header {
  background-color: white;
  color: #333;
  border-bottom: 1px solid #eee;
}

.private-tag {
  font-size: 0.8rem;
  background-color: #3498db;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 0.5rem;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.9rem;
}

.status-indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.connection-status.connected .status-indicator {
  background-color: #2ecc71;
}

.connection-status.connecting .status-indicator {
  background-color: #f39c12;
}

.connection-status.disconnected .status-indicator {
  background-color: #e74c3c;
}

.messages {
  flex: 1;
  padding: 1.5rem;
  overflow-y: auto;
  background-color: #f9f9f9;
  background-image: 
    linear-gradient(rgba(240, 240, 240, 0.8) 1px, transparent 1px),
    linear-gradient(90deg, rgba(240, 240, 240, 0.8) 1px, transparent 1px);
  background-size: 20px 20px;
}

.message {
  max-width: 70%;
  margin-bottom: 1rem;
  padding: 0.75rem 1rem;
  border-radius: 18px;
  position: relative;
  animation: fadeIn 0.3s ease;
}

.message.sent {
  background-color: #2ecc71;
  color: white;
  align-self: flex-end;
  margin-left: auto;
  border-top-right-radius: 4px;
}

.message:not(.sent) {
  background-color: white;
  border-top-left-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.system-message {
  color: rgba(235, 179, 97, 0.8);
  text-align: center;
  font-size: 0.9rem;
  padding: 0.5rem 1rem;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 12px;
}

.message-sender {
  font-size: 0.8rem;
  color: #666;
  margin-bottom: 0.25rem;
  font-weight: 500;
}

.message-time {
  font-size: 0.75rem;
  margin-top: 0.25rem;
  opacity: 0.7;
  text-align: right;
}

.message-self {
  font-size: 0.75rem;
  margin-top: 0.25rem;
  text-align: right;
  opacity: 0.7;
}

.message-input-area {
  display: flex;
  padding: 1rem;
  background-color: white;
  border-top: 1px solid #eee;
  gap: 1rem;
}

.message-input-area textarea {
  flex: 1;
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 24px;
  resize: none;
  font-size: 1rem;
  min-height: 50px;
}

.message-input-area textarea:focus {
  outline: none;
  border-color: #3498db;
}

.send-btn {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #3498db;
  color: white;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.send-btn:hover {
  background-color: #2980b9;
}

.send-btn:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #bbb;
}
/* 原有样式保持不变 */
.chat-system {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  color: #333;
  overflow: hidden;
}

.chat-header {
  background-color: #2c3e50;
  color: white;
  padding: 1rem 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

/* 省略中间原有样式... */

/* 表情功能相关样式 */
.message-input-area {
  display: flex;
  padding: 1rem;
  background-color: white;
  border-top: 1px solid #eee;
  gap: 0.5rem;
  position: relative;
}

.emoji-container {
  position: relative;
  display: flex;
  flex-direction: column;
}

.emoji-btn {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 4px;
  color: #666;
  transition: background-color 0.2s;
}

.emoji-btn:hover {
  background-color: #f0f0f0;
}

.emoji-panel {
  position: absolute;
  bottom: 100%;
  left: 0;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 1rem;
  margin-bottom: 0.5rem;
  width: 300px;
  max-height: 250px;
  overflow-y: auto;
  z-index: 100;
}

.emoji-category h4 {
  margin-bottom: 0.5rem;
  color: #666;
  font-size: 0.9rem;
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 0.5rem;
}

.emoji-item {
  font-size: 1.2rem;
  text-align: center;
  padding: 0.25rem;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.emoji-item:hover {
  background-color: #f0f0f0;
}

.message-input-area textarea {
  flex: 1;
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 24px;
  resize: none;
  font-size: 1rem;
  min-height: 50px;
}

.send-btn {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #3498db;
  color: white;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

/* 其他原有样式保持不变 */
</style>
    